<template>
  <div class="page-container" ref="page">
    <list-searcher
      :searchList="searchList"
      v-model:searchForm="queryParam"
      @submit="handleSubmit"
      @reset="handleReset"
      style="position: relative"
    />
    <div style="position: absolute; top: 25px; left: 25px">
      <a-tooltip content="报表周期可显示前3个月和未来1个月的数据" position="top" mini trigger="click">
        <icon-question-circle style="font-size: 16px" />
      </a-tooltip>
    </div>
    <template v-if="toSearchFlag">
      <a-row style="margin-bottom: 16px">
        <a-col flex="600px">
          <div>
            <span style="font-size: 14px; color: #4e5969">门店总收益：</span>
            <span style="font-size: 14px; color: #1890ff">{{ allRevenue || '-' }}元</span>
          </div>
        </a-col>
        <a-col flex="auto">
          <div></div>
        </a-col>
        <a-col flex="164px">
          <div class="flex">
            <a-button @click="changeToggleStatus">切换报表</a-button>
            <a-button style="margin-left: 16px" type="primary" @click="handleExport">导出</a-button>
          </div>
        </a-col>
      </a-row>
    </template>

    <template v-if="toSearchFlag">
      <a-table :columns="columns" :data="data" v-if="toggleStatus == 0" :pagination="false" :loading="tableLoading">
        <template #siteName="{ record }">
          <div style="max-width: 150px; min-width: 120px; padding-right: 24px">
            <a-tooltip :content="record.siteName">
              <div class="ellipsis-text">{{ record.siteName }}</div>
            </a-tooltip>
          </div>
        </template>

        <template #recordRender="{ record, column, rowIndex }">
          <RecordRender :record="record[column.dataIndex]" />
        </template>
      </a-table>
      <a-row style="margin-top: 24px" v-if="toggleStatus == 0">
        <a-col style="display: flex; justify-content: space-between; align-items: center">
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              font-size: 14px;
              font-weight: 400;
              color: #1d2129;
              width: 184px;
            "
            >每页展示
            <a-select
              :options="paginationOptions"
              v-model="pageSelect"
              :allow-clear="false"
              size="small"
              style="width: 70px"
              @change="changePageSelect"
            />
            项结果
          </div>
          <a-pagination
            :total="totalData"
            show-total
            @change="changePagination"
            show-page-size
            v-model:page-size="pageSelect"
            :current="currentPage"
          />
        </a-col>
      </a-row>
    </template>

    <div id="myEcharts" ref="my_echarts" v-show="toggleStatus == 1 && toSearchFlag"></div>

    <div class="data-empty" v-if="!toSearchFlag">
      <a-empty> 暂无数据，请选择周期 </a-empty>
    </div>
  </div>
</template>

<script setup name="StoreRevenueReportList">
  import { ref, reactive, onMounted, computed, nextTick } from 'vue'
  import { storeRevenueList, storeRevenueChart, exportStoreRevenue, getStoreAllRevenue } from '@/api/reportForms/storeRevenueReport'
  import { useExport } from '@/hooks/list'
  import RecordRender from './components/record-render.vue'
  import { Message } from '@arco-design/web-vue'
  import * as echarts from 'echarts'
  import { graphic } from 'echarts'
  const toggleStatus = ref(0)

  const pageSelect = ref(10)
  const currentPage = ref(1)
  const tableLoading = ref(false)
  const toSearchFlag = ref(false)

  const allRevenue = ref(0)
  const chartXAxisData = ref([])
  const chartXCYSeriesData = ref([]) //携程
  const chartWKYSeriesData = ref([]) //悟空
  const chartTXYSeriesData = ref([]) //铁行
  const chartFzYSeriesData = ref([]) //飞租
  const chartDDYSeriesData = ref([]) //滴滴
  const chartQTYSeriesData = ref([]) //其他
  const chartHLYSeriesData = ref([]) //哈啰
  const chartFZYSeriesData = ref([]) //飞猪
  const chartZYYSeriesData = ref([]) //自营

  const paginationOptions = reactive([
    { value: 10, label: '10' },
    { value: 20, label: '20' },
    { value: 50, label: '50' },
  ])

  // 查询条件
  const searchList = computed(() => {
    return [
      {
        label: '报表周期',
        prop: 'queryDate',
        type: 'i-range-picker',
        // disabledDate: (current) => {
        //   const today = dayjs().startOf('day')
        //   const cur = dayjs(current)
        //   return cur.isBefore(today.subtract(3, 'month')) || cur.isAfter(today.add(1, 'month'))
        // },
        change: (value = []) => {
          queryParam.startDate = value[0]
          queryParam.endDate = value[1]
        },
      },
      {
        label: '归属门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
        },
      },
    ]
  })

  const tooltipItemsHtmlString = (items) => {
    return items
      .map(
        (el) => `<div class="content-panel" style="display: flex;
    justify-content: space-between;
    padding: 0 9px;
    background: rgba(255, 255, 255, 0.8);
    width: 164px;
    height: 32px;
    line-height: 32px;
    box-shadow: 6px 0px 20px rgba(34, 87, 188, 0.1);
    border-radius: 4px;
    margin-bottom: 4px;">
        <p style="margin: 0;padding: 0;">
          <span style="background-color: ${el.color};display: inline-block;
    margin-right: 8px;
    width: 10px;
    height: 10px;
    border-radius: 50%;" ></span>
          <span>${el.seriesName}</span>
        </p>
        <span style="font-size: 13px;
    line-height: 15px;
    display: flex;
    align-items: center;
    text-align: right;
    color: #1d2129;
    font-weight: bold;">
        ${el.value}元
        </span>
      </div>`
      )
      .join('')
  }

  function graphicFactory(side) {
    return {
      type: 'text',
      bottom: '8',
      ...side,
      style: {
        text: '',
        textAlign: 'center',
        fill: '#4E5969',
        fontSize: 12,
      },
    }
  }
  const graphicElements = ref([graphicFactory({ left: '2.6%' }), graphicFactory({ right: 0 })])
  const colors = reactive(['#246EFF'])
  const myEcharts = echarts

  const initChart = () => {
    let chart = myEcharts.init(document.getElementById('myEcharts'), 'purple-passion')
    chart.setOption({
      // color: colors,
      grid: {
        left: '4%',
        right: 0,
        top: '20',
        bottom: '60',
      },
      legend: {
        bottom: 0,
        icon: 'circle',
        textStyle: {
          color: '#4E5969',
        },
      },
      xAxis: {
        type: 'category',
        data: chartXAxisData.value,
        axisLine: {
          lineStyle: {
            color: '#A9AEB8',
          },
        },
        axisTick: {
          show: true,
          alignWithLabel: true,
          lineStyle: {
            color: '#86909C',
          },
        },
        axisLabel: {
          color: '#86909C',
        },
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          color: '#86909C',
          formatter(value, idx) {
            if (idx === 0) return `${value}`
            return `${value / 1000}k`
          },
        },
        splitLine: {
          lineStyle: {
            color: '#E5E6EB',
          },
        },
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        formatter(params) {
          // let firstElement = {}
          let todayRevenueCost = 0
          params.forEach((item) => {
            // firstElement = {
            //   axisDim: item.axisDim,
            //   axisIndex: item.axisIndex,
            //   axisType: item.axisType,
            //   axisId: item.axisId,
            //   axisValue: item.axisValue,
            //   axisValueLabel: item.axisValueLabel,
            // }
            todayRevenueCost += item.value
          })
          return `<div style="background: linear-gradient(
          304.17deg,
          rgba(253, 254, 255, 0.6) -6.04%,
          rgba(244, 247, 252, 0.6) 85.2%
        ) !important;margin:-10px;padding:10px;">
                  <p style="font-size: 13px;
          line-height: 15px;
          display: flex;
          align-items: center;
          text-align: right;
          color: #1d2129;
          font-weight: bold;margin:0;padding:0;margin-bottom:8px;">订单总收益：${todayRevenueCost}元</p>
                  ${tooltipItemsHtmlString(params)}
                </div>`
        },
        className: 'echarts-tooltip-diy',
      },
      series: [
        {
          name: '携程',
          data: chartXCYSeriesData.value,
          stack: 'one',
          type: 'bar',
          barWidth: 16,
          color: '#00B2FF',
        },
        {
          name: '飞猪',
          data: chartFZYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#FFE180',
        },
        {
          name: '哈啰',
          data: chartHLYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#80E2FF',
          itemStyle: {
            borderRadius: 2,
          },
        },
        {
          name: '悟空',
          data: chartWKYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#F68B8B',
        },
        {
          name: '铁行',
          data: chartTXYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#56E2A8',
        },
        {
          name: '飞租',
          data: chartFzYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#76C204',
        },
        {
          name: '滴滴',
          data: chartDDYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#546570',
        },
        {
          name: '其他',
          data: chartQTYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#B5C4C8',
        },
        {
          name: '自营',
          data: chartZYYSeriesData.value,
          stack: 'one',
          type: 'bar',
          color: '#246EFF',
        },
      ],
    })
    window.onresize = function () {
      chart.resize()
    }
  }

  const queryParam = reactive({
    pageSize: 10,
    pageNumber: 1,
    siteIdList: [],
    queryDate: [],
  })

  const totalData = ref(0)

  // table 配置
  const columns = ref([
    { title: '门店', dataIndex: 'siteName', slotName: 'siteName', width: 150 },
    { title: '订单总数', dataIndex: 'totalCount', width: 110 },
    {
      title: '订单取消率',
      width: 120,
      dataIndex: 'cancelRate',
      render: (record) => {
        if (record.record.cancelRate) {
          return record.record.cancelRate + '%'
        }
      },
    },
    { title: '总收益(元)', dataIndex: 'totalAmount', width: 110 },
  ])

  const data = ref([])
  // 导出事件
  const handleExport = () => {
    useExport(exportStoreRevenue, queryParam)
  }

  const my_echarts = ref(null)
  //切换报表
  const changeToggleStatus = () => {
    if (toggleStatus.value == 0) {
      toggleStatus.value = 1
      myEcharts.dispose
      getChartList()
    } else {
      queryParam.pageNumber = 1
      toggleStatus.value = 0
      getDataList()
    }
  }

  /**
   * 获取图表
   */
  const getChartList = () => {
    storeRevenueChart({ siteIdList: queryParam.siteIdList, startDate: queryParam.startDate, endDate: queryParam.endDate }).then((res) => {
      if (res.code == 200) {
        // 清空数据
        chartXAxisData.value = []
        chartXCYSeriesData.value = []
        chartWKYSeriesData.value = []
        chartTXYSeriesData.value = []
        chartQTYSeriesData.value = []
        chartHLYSeriesData.value = []
        chartFZYSeriesData.value = []
        chartZYYSeriesData.value = []
        const result = res.result
        if (result.length) {
          chartXAxisData.value = result[0].x
          result.forEach((item) => {
            if (item.name == '哈啰') {
              chartHLYSeriesData.value = item.y
            }
            if (item.name == '携程') {
              chartXCYSeriesData.value = item.y
            }
            if (item.name == '悟空') {
              chartWKYSeriesData.value = item.y
            }
            if (item.name == '铁行') {
              chartTXYSeriesData.value = item.y
            }
            if (item.name == '飞租') {
              chartFzYSeriesData.value = item.y
            }
            if (item.name == '滴滴') {
              chartDDYSeriesData.value = item.y
            }
            if (item.name == '其他') {
              chartQTYSeriesData.value = item.y
            }
            if (item.name == '飞猪') {
              chartFZYSeriesData.value = item.y
            }
            if (item.name == '自营') {
              chartZYYSeriesData.value = item.y
            }
          })
        }
        initChart()
      }
    })
  }

  /**
   * 查询门店总收益
   */
  const getStoreAllRevenueApi = () => {
    getStoreAllRevenue({ startDate: queryParam.startDate, endDate: queryParam.endDate, siteIdList: queryParam.siteIdList }).then((res) => {
      if (res.code == 200) {
        allRevenue.value = res.result
      }
    })
  }
  /**
   * 切换分页
   */
  const changePagination = (e) => {
    console.log(e)
    queryParam.pageNumber = e
    currentPage.value = e
    handleSubmit('pageNumber')
  }

  /**
   * 切换每页展示个数
   */
  const changePageSelect = (e) => {
    console.log(e)
    queryParam.pageSize = e
    handleSubmit('pageSize')
  }

  //重置
  const handleReset = () => {
    data.value = []
    toggleStatus.value = 0
    toSearchFlag.value = false
  }

  /**
   * 查询列表/图表
   * toggleStatus.value = 0 查询列表
   * toggleStatus.value = 1 查询图表
   */
  const handleSubmit = (e) => {
    if (!queryParam.queryDate || queryParam.queryDate.length == 0) {
      Message.warning('请选择报表周期后查询')
      return
    }
    if (!e || e == 'pageSize') {
      queryParam.pageNumber = 1
      currentPage.value = 1
    }
    if (toggleStatus.value == 0) {
      getDataList()
      getStoreAllRevenueApi()
    } else {
      getChartList()
      getStoreAllRevenueApi()
    }
  }

  const tableMinWidth = computed(() => {
    return columns.value.length * 120
  })
  const page = ref(null)

  /**
   * 查询列表
   */
  const getDataList = () => {
    toSearchFlag.value = true
    tableLoading.value = true
    storeRevenueList({ ...queryParam }).then(async (res) => {
      tableLoading.value = false
      if (res.code == 200) {
        data.value = []
        columns.value = columns.value.slice(0, 4)
        await nextTick()
        const result = res.result.data
        if (result.length > 0) {
          result.forEach((item) => {
            let dateTimeList = item.data
            if (Array.isArray(dateTimeList) && dateTimeList.length > 0) {
              dateTimeList.forEach((dateTimeItem, index) => {
                item[`dataTime${index}`] = dateTimeItem || {}
              })
            }
          })
          data.value = result
          totalData.value = res.result.total
          const date = result[0].data
          date.forEach((item, index) => {
            columns.value.push({
              width: 120,
              title: item.date,
              align: 'left',
              dataIndex: 'dataTime' + index,
              slotName: 'recordRender',
            })
          })
          if (tableMinWidth.value < page.value.clientWidth) {
            columns.value.push({
              title: '',
              dataIndex: 'dataTime--1',
            })
          }
        }
      }
    })
  }
  onMounted(() => {
    initChart()
  })
</script>

<style lang="less" scoped>
  #myEcharts {
    width: calc(100vw - 300px);
    height: 400px;
  }
  .echarts-tooltip-diy {
    background: linear-gradient(304.17deg, rgba(253, 254, 255, 0.6) -6.04%, rgba(244, 247, 252, 0.6) 85.2%) !important;
    border: none !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 6px !important;
    .content-panel {
      display: flex;
      justify-content: space-between;
      padding: 0 9px;
      background: rgba(255, 255, 255, 0.8);
      width: 164px;
      height: 32px;
      line-height: 32px;
      box-shadow: 6px 0px 20px rgba(34, 87, 188, 0.1);
      border-radius: 4px;
      margin-bottom: 4px;
    }
    .tooltip-title {
      margin: 0 0 10px 0;
    }
    p {
      margin: 0;
    }
    .tooltip-title,
    .tooltip-value {
      font-size: 13px;
      line-height: 15px;
      display: flex;
      align-items: center;
      text-align: right;
      color: #1d2129;
      font-weight: bold;
    }
    .tooltip-item-icon {
      display: inline-block;
      margin-right: 8px;
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
  }
  .data-empty {
    margin-top: 100px;
  }
  .ellipsis-text {
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-line-clamp: 1;
    display: -webkit-box;
    -webkit-box-orient: vertical;
  }
  :deep(.arco-pagination-options) {
    display: none;
  }
</style>
